package class03;

import utils.ArrayUtil;

import java.util.Arrays;

public class Code02_二分查找大于最左 {
    public static void main(String[] args) {
        int times = 100;
        for (int i = 0; i < times; i++) {
            int[] arr = ArrayUtil.generateRandomArray(100, 1000, false, true);
            int num = arr[10];
            Arrays.sort(arr);
            int moreNearLeftIndex1 = findMoreNearLeft(arr, num);
            int moreNearLeftIndex2 = force(arr, num);
            if (moreNearLeftIndex1 != moreNearLeftIndex2) {
                System.out.println("fuck error");
                ArrayUtil.printArray(arr);
                System.out.println(num);
                System.out.println("moreNearLeftIndex1:" + moreNearLeftIndex1);
                System.out.println("moreNearLeftIndex2:" + moreNearLeftIndex2);
            }

        }
        System.out.println("over");
    }

    /**
     * 二分查找  有序数组中 查找大于等于给定数的最左位置
     */
    public static int findMoreNearLeft(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return -1;
        }
        int ans = -1;
        int L = 0;
        int R = arr.length - 1;
        while (L <= R) {
            int middle = L + ((R - L) >> 1);
            if (arr[middle] >= num) {
                ans = middle;
                R = middle - 1;
            } else {
                L = middle + 1;
            }
        }
        return ans;
    }

    /**
     * 暴力从左到右查大于等于num的最左
     */
    public static int force(int[] arr, int num) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= num) {
                return i;
            }
        }
        return -1;
    }
}
